package com.consumer0.demo;

import com.jobs.common.factory.RabbitMqUtils;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.util.concurrent.TimeUnit;


/**
 * 消费者
 * @author  xdh
 */
public class Worker03_2 {
    // 队列名称
    public static final String TASK_QUEUE_NAME = "ack_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        System.out.println("C2等待接受消息处理时间较长");

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            System.out.println("C2接受到的消息是:"+new String(message.getBody()));
            // 沉睡一秒
            try {
                TimeUnit.SECONDS.sleep(40);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("C2消息处理完成:"+new String(message.getBody()));
            //进行手动应答
            /*
             * 参数1：消息的标记  tag
             * 参数2：是否批量应答，false：不批量应答 true：批量
             * */
            long deliveryTag = message.getEnvelope().getDeliveryTag();
            channel.basicAck(deliveryTag,false);
        };


        // 采用手动应答
        boolean autoAck = false;

        CancelCallback cancelCallback = (consumerTag) -> {
            System.out.println(consumerTag+"消费者取消消费接口回调逻辑");
        };

        channel.basicConsume(TASK_QUEUE_NAME, autoAck, deliverCallback, cancelCallback);
    }
}
